<template>
    <div class="app-container">
        <a-button type="primary" @click="(openModal as any)">新增科目</a-button>
        <div class="table-head">
            <div>科目名称</div>
            <div>排序</div>
            <div>科目编码</div>
            <div>账户类别</div>
            <div>初期金额</div>
            <div>操作</div>
        </div>
        <a-empty v-if="!data.length"></a-empty>
        <a-scrollbar style="max-height:calc(100vh - 300px);overflow-y: scroll;">
            <Tree :data="data" :type="type">
                <template #btn="{ row }">
                    <a-button type="text" v-if="row.subjectCode.length != 8 && row.source"
                        @click="openModal(row)">添加</a-button>
                    <a-button type="text" @click="openModal(row, true)">编辑</a-button>
                    <a-button type="text" @click="openDel(row)" v-if="row.source">删除</a-button>
                </template>
                <template #input="{ row }">
                    <a-input-number v-if="row.source" style="width: 70px;" :min="1" v-model="row.sort"
                        @blur="changeSort(row)"></a-input-number>
                        <div v-else>{{ row.sort }}</div>
                </template>
            </Tree>
        </a-scrollbar>
        <a-modal v-model:visible="visible" hide-title @ok="confirm" @cancel="close" :on-before-ok="(verify as any)"
            unmountOnClose>
            <CustomTitle :title="modelTitle" style="margin-bottom: 20px;" />
            <a-form :model="form" :rules="rules" ref="formRef">
                <a-form-item label="上一级科目" v-if="!child">
                    <div>{{ addRow.name }}</div>
                </a-form-item>
                <a-form-item label="账户类别" v-if="!child">
                    <div>{{ type[addRow.type as any] }}</div>
                </a-form-item>
                <a-form-item label="科目名称" field="subjectName">
                    <a-input v-model="form.subjectName" placeholder="请输入科目名称" v-if="form.source"></a-input>
                    <div v-else class="preview">{{ form.subjectName }}</div>
                </a-form-item>
                <a-form-item label="科目编码" field="subjectCode">
                    <a-input v-if="form.source" :placeholder="child ? '请输入四位整数' : '请输入两位整数'" allow-clear
                        v-model="form.subjectCode">
                        <template #prepend v-if="!child">
                            <span>{{ addRow.code }}</span>
                        </template>
                    </a-input>
                    <div v-else class="preview">{{ addRow.code }} {{ form.subjectCode }}</div>
                </a-form-item>
                <a-form-item label="账户类别" v-if="child" field="subjectType">
                    <a-radio-group v-if="form.source" v-model="form.subjectType">
                        <a-radio v-for="item, index in type" :key="item" :value="Number(index)">{{ item }}</a-radio>
                    </a-radio-group>
                    <div v-else class="preview">{{ type[form.subjectType] }}</div>
                </a-form-item>
                <a-form-item label="期初金额" field="money">
                    <a-input v-model="form.money" placeholder="请输入正数，支持小数点"></a-input>
                </a-form-item>
                <a-form-item label="排序" field="sort">
                    <a-input-number v-if="form.source" style="width: 150px;" v-model="form.sort" mode="button"
                        :min="1" />
                    <div v-else class="preview">{{ form.sort }}</div>
                </a-form-item>
            </a-form>
        </a-modal>
        <!--  删除角色/账户弹窗 -->
        <a-modal v-model:visible="delVisible" @ok="del" okText="确定" cancelText="取消" width="400px" :mask-closable="false"
            unmountOnClose :closable="false">
            <div class="modal-message">
                <div class="del-name">{{ delDetail.subjectName }}</div>
                <div class="del-tip">确认删除该节点及子节点的内容？</div>
            </div>
        </a-modal>
    </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import Tree from "./components/Tree.vue";
import CustomTitle from "@/components/CustomTitle/index.vue";
import { getFinanceSubjectList, addFinanceSubject, editFinanceSubject, delFinanceSubject } from "@/apis/system";
import type { financeSubjectsParams } from "@/apis/system/type";
import { Message } from '@arco-design/web-vue';

const data = ref([]);
const visible = ref(false);
const type: { [key: number]: string } = {
    1: '资产',
    2: '负债',
    3: '权益',
    4: '损益-收入',
    5: '损益-费用'
}
const delVisible = ref(false);
const formRef = ref(null);
const addRow = ref({
    name: '',
    type: 1,
    code: ''
})
const defaultItem = {
    sort: 1,
    subjectType: 1,
    money: '',
    subjectName: '',
    parentSubjectId: undefined,
    subjectCode: '',
    source: 1
}
const reset = () => {
    (formRef as any).value.resetFields();
    form.value = { ...JSON.parse(JSON.stringify(defaultItem)) };
    form.value = { ...JSON.parse(JSON.stringify(defaultItem)) };
}
const delDetail = ref<financeSubjectsParams>({
    ...JSON.parse(JSON.stringify(defaultItem))
})
const form = ref<financeSubjectsParams>({
    ...JSON.parse(JSON.stringify(defaultItem))
});
const isNew = ref(true);
const openDel = (row: financeSubjectsParams) => {
    delDetail.value = { ...row };
    delVisible.value = true;
}
const del = async () => {
    await delFinanceSubject(delDetail.value.subjectId as string);
    init();
    Message.success('删除成功');
}
const init = async () => {
    const res = await getFinanceSubjectList();
    data.value = res.data;
}
const close = () => {
    visible.value = false;
    reset();
}
const verify = () => {
    const result = new Promise(async resolve => {
        (formRef as any).value.validate((errors: any) => {
            resolve(errors == void 0);
        })
    })
    return result;
}
const confirm = async () => {
    const close = (res: { code: number }) => {
        if (res.code == 200) {
            init();
            Message.success('操作成功')
            reset();
        }
        return res.code == 200;
    }
    if (isNew.value) {
        const res = await addFinanceSubject(form.value);
        return close(res)
    } else {
        const res = await editFinanceSubject(form.value);
        return close(res)
    }
}
const changeSort = (row: financeSubjectsParams) => {
    form.value = { ...row };
    isNew.value = false;
    confirm();
}
const child = ref()
const modelTitle = ref('新增科目');
const isChild = (row: financeSubjectsParams, isEdit = false) => {
    if (!row.subjectId) {
        modelTitle.value = '新增科目';
        child.value = true;
    } else {
        if (isEdit) {
            if (row.subjectCode.length == 4) {
                modelTitle.value = '编辑科目';
                child.value = true;
            } else {
                modelTitle.value = '编辑子科目';
                child.value = false;
            }
        } else {
            modelTitle.value = '新增子科目';
            child.value = false;
        }
    }
};
const getParent = (treeData: any[], parentSubjectId: string) => {
    treeData.forEach(item => {
        if (item.subjectId == parentSubjectId) {
            addRow.value = {
                name: item.subjectName,
                type: item.subjectType,
                code: item.subjectCode
            }
        } else if (item.children && item.children.length) {
            getParent(item.children, parentSubjectId)
        }
    })
}
const openModal = (row: financeSubjectsParams, isEdit = false) => {
    isChild(row, isEdit);
    if (!isEdit) {
        isNew.value = true;
        if (row.subjectId) {
            form.value.parentSubjectId = row.subjectId;
            addRow.value = {
                name: row.subjectName,
                type: row.subjectType,
                code: row.subjectCode
            }
        }
    } else {
        isNew.value = false;
        form.value = { ...row, subjectCode: row.parentSubjectId ? row.subjectCode.slice(-2) : row.subjectCode };
        form.value = { ...row, subjectCode: row.parentSubjectId ? row.subjectCode.slice(-2) : row.subjectCode };
        if (row.parentSubjectId) {
            getParent(data.value, row.parentSubjectId);
        }
    }
    visible.value = true;
}
const validator = (value: string, callback: Function) => {
    const reg = new RegExp('^\\d{' + (child.value ? 4 : 2) + '}$');
    if (reg.test(value)) {
        callback();
    } else {
        callback(`请输入${child.value ? 4 : 2}位数字的科目编码`,)
    }
}
const rules = {
    subjectName: [
        { required: true, message: '请输入科目名称', trigger: 'blur' },
        { maxLength: 32, message: '科目名称不能超过32个字符', trigger: 'blur' }
    ],
    subjectType: [
        { required: true, message: '请选择账户类别', trigger: 'blur' },
    ],
    subjectCode: [
        { required: true, message: '请输入科目编码', trigger: 'blur' },
        { validator, trigger: 'blur' }
    ],
    money: [
        { required: true, message: '请输入期初金额', trigger: 'blur' },
        { match: /^[0-9]+(\.[0-9]{1,2})?$/, message: '请输入正确的金额', trigger: 'blur' }
    ],
    sort: [{ required: true, message: '请输入排序', trigger: 'blur' }]
}

onMounted(() => {
    init();
})
</script>

<style lang="scss" scoped>
.table-head {
    height: 50px;
    display: grid;
    grid-template-columns: 2fr repeat(4, 1fr) 2fr;
    background: #F2F6FC;
    line-height: 50px;
    text-align: center;
    margin: 20px 0 10px;

    >div:first-child {
        text-align: left;
        padding-left: 20px;
    }
}

.arco-radio-group {
    line-height: 36px;
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    grid-template-columns: repeat(3, 1fr);
}

.modal-message {
    text-align: center;

    .del-name {
        width: 80%;
        margin: 12px auto;
        height: 60px;
        line-height: 60px;
        border: 1px solid #DCDFE6;
    }
}

.preview {
    width: 100%;
    border: 1px solid #DCDFE6;
    height: 32px;
    line-height: 32px;
    padding: 0 10px;
}
</style>
